<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 先序 + 中序遍历，我们可以确定二叉树。先确定根节点，左右子树。同理，递归
    var buildTree = function (preorder, inorder) {
      if (preorder.length == 0 || inorder.length == 0) return null
      const index = inorder.findIndex(itme => itme === preorder[0])
      const left = inorder.slice(0, index)
      const right = inorder.slice(index + 1)
      return {
        root: preorder[0],
        left: buildTree(preorder.slice(1, index + 1), left),
        right: buildTree(preorder.slice(index + 1), right)
      }
    }
    console.log(buildTree(preorder = [3, 9, 20, 15, 7], inorder = [9, 3, 15, 20, 7]))
  </script>
</body>

</html>